package persistent;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;

import frame.Frame;

public class Persistent extends Thread {
	
	protected boolean active = true;
	
	private File logFile;
	
	private BlockingQueue<Frame> persistentQueue;
	
	public Persistent(BlockingQueue<Frame> persistentQueue){
		
		this.persistentQueue = persistentQueue;
		
		logFile = new File("LogVehiculos_Respaldo.log");
	}
	
	@Override
	public void run(){
		
		while(active){
			
			try {
				Thread.sleep(1000);
				
				if(persistentQueue.size() > 0){
					BufferedWriter bw = new BufferedWriter(new FileWriter(logFile, true));
					
					for(int i=0; i<persistentQueue.size(); i++){
						bw.write(persistentQueue.take().toString() + "\n");
					}
					
					bw.close();
				}
			} 
			catch (InterruptedException e) {
				e.printStackTrace();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
